package com.example.myapplication;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //创建Button对象   也就是activity_main.xml里所设置的ID
    Button add, Calculation, reset;
    EditText price, editText3, maxPrice;
    TextView editText5, editText2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //实例化对象
        setContentView(R.layout.activity_main);
        add = (Button) findViewById(R.id.add);
        price = (EditText) findViewById(R.id.price);
        editText3 = (EditText) findViewById(R.id.editText3);
        editText2 = (TextView) findViewById(R.id.editText2);
        editText5 = (TextView) findViewById(R.id.editText5);
        editText5.setMovementMethod(ScrollingMovementMethod.getInstance());
        maxPrice = (EditText) findViewById(R.id.maxPrice);
        Calculation = (Button) findViewById(R.id.Calculation);
        reset = (Button) findViewById(R.id.reset);
        //给按钮设置的点击事件
        add.setOnClickListener(this);
        Calculation.setOnClickListener(this);
        reset.setOnClickListener(this);
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.add:
                String text = price.getText().toString();
                if (text == null || text.length() == 0) {
                    toast("请先输入价格！");
                    return;
                }
                editText3.setText(editText3.getText().toString() + price.getText().toString() + " ");
                price.setText("");
                break;
            case R.id.Calculation:
                editText5.setText("");
                Calculation();
                hideKeyboard(v.getWindowToken());
                break;
            case R.id.reset:
                editText3.setText("");
                price.setText("");
                maxPrice.setText("");
                editText5.setText("");
        }
//        BigDecimal i1 = new BigDecimal("20");
//        BigDecimal i2 = new BigDecimal("48");
//        BigDecimal i3 = new BigDecimal("29.9");
//        BigDecimal i4 = new BigDecimal("25");
        //满减价格
//        BigDecimal count = new BigDecimal("90");
//        list.add(i1);
//        list.add(i2);
//        list.add(i3);
//        list.add(i4);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void Calculation() {
        String maxPrice1 = maxPrice.getText().toString();
        String allPrice = editText3.getText().toString();
        if (allPrice == null || allPrice.length() == 0) {
            toast("价格不能为空");
            return;
        }
        if (maxPrice1 == null || maxPrice1.length() == 0) {
            toast("满减价格不能为空");
            return;
        }
        BigDecimal count = new BigDecimal(maxPrice1);
        List<BigDecimal> list = new ArrayList<>();
        String[] s = allPrice.split(" ");
        list = Arrays.asList(s).stream().distinct().map(x -> BigDecimal.valueOf(Double.valueOf(x))).collect(Collectors.toList());
        count(list, count);
    }

    public void showText(String message) {
        AlertDialog alertDialog2 = new AlertDialog.Builder(this)
                .setTitle("计算结果")
                .setMessage(message)
                .setIcon(R.mipmap.ic_launcher)
                .setPositiveButton("确定", null
//                        new DialogInterface.OnClickListener() {//添加"Yes"按钮
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
////                        Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
//                    }
//                }
                )
                .create();
        alertDialog2.show();
    }


    public void toast(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }

    public void alert(String title, String message) {
        AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                .setTitle(title == null ? "错误提示" : title)//标题
                .setMessage(message == null ? "错误提示" : message)//内容
                .setIcon(R.mipmap.ic_launcher)//图标
                .create();
        alertDialog1.show();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void count(List<BigDecimal> list, BigDecimal count) {
        BigDecimal low = list.stream().min((x1, x2) -> x1.compareTo(x2)).get();
        System.out.println("传入参数");
//        list.stream().forEach(System.out::println);
        System.out.println("每个商品可购买的最多件数");
        //计算每个商品最多可以买多少件划算，第一个参数保存最多多少件，第二个参数保存购买后的价格
        List<BigDecimal[]> all = new ArrayList<>();
        //对价格排序
        List<BigDecimal> sort = list.stream().sorted().collect(Collectors.toList());
        sort.stream().forEach((x) -> {
            Integer max = (count.intValue() % x.intValue() == 0 ? count.intValue() / x.intValue() : count.intValue() / x.intValue() + 1);
            BigDecimal[] b = {BigDecimal.valueOf(max), x.multiply(BigDecimal.valueOf(max))};
            all.add(b);
            System.out.println("价格为  " + x + "  可以买  " + max + "  件,总价为" + x.multiply(BigDecimal.valueOf(max)));
        });
        //取出话最多钱买的商品的那一个数组，之后凑单价格不能超过这个，超过及作废
        BigDecimal[] maxPrice = all.stream().max((x, y) -> x[1].compareTo(y[1])).get();
        List<List<BigDecimal>> lists = new ArrayList<>();
        all.stream().forEach(x -> {
            List<BigDecimal> l = new ArrayList<>();
            for (int i = 0; i <= x[0].intValue(); i++) {
                l.add(BigDecimal.valueOf(i));
            }
            lists.add(l);
        });
//        lists.stream().forEach(System.out::println);
        List<String> result = Arrays.asList(multiRound(lists, "", 0).split("\n"));
        //计算最后的价格
        //接受返回的集合
        List<String[]> res = new ArrayList<>();
        List<String[]> list1 = countPrice(result, sort, count, maxPrice[1], res);
        StringBuffer sb = new StringBuffer();
        list1.stream()
                .sorted((x, y) -> BigDecimal.valueOf(Double.valueOf(x[1])).compareTo(BigDecimal.valueOf(Double.valueOf(y[1]))))
                .limit(10)
                .map(s -> s[0])
                .forEach(s -> {
                    sb.append(editText5.getText().toString() + s + "\n");
//                    editText5.setText(editText5.getText().toString() + s + "\n");
                });
        showText(sb.toString());
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public List<String[]> countPrice(List<String> result, List<BigDecimal> sort, BigDecimal minPrice, BigDecimal maxPrice, List<String[]> res) {
        result.stream().forEach(s -> {
            String[] string = s.split("/");
            StringBuffer sb = new StringBuffer("");
            BigDecimal price = new BigDecimal("0");
            for (int i = 0; i < string.length; i++) {
                //价格就算表达式
                price = price.add(BigDecimal.valueOf(Long.valueOf(string[i])).multiply(sort.get(i)));
                sb.append(string[i]).append(" * ").append(sort.get(i));
                if (i < string.length - 1) {
                    sb.append(" + ");
                }
            }
            if (price.compareTo(minPrice) == 1 && maxPrice.compareTo(price) == 1) {
                sb.append(" = ").append(price);
                String[] ss = {sb.toString(), price.toString()};
                res.add(ss);
            }
        });
        return res;
    }

    public static String multiRound(List<List<BigDecimal>> dataList, String temp, int index) {
        if (index >= dataList.size()) {
            return "";
        }
        StringBuffer out = new StringBuffer();
        String tmp = "";
        //取出第一个list
        List<BigDecimal> data = dataList.get(index);
        //对第一个list进行遍历
        for (int i = 0; i < data.size(); i++) {
            tmp = data.get(i) + "/";
            if (index < dataList.size()) {
//取出第一个list中的参数进行拼接，进入下面的循环，取出第二个list，以此继续循环至最后一个list中的最后一个参数，然后再取出第二个参数，继续循环
                out.append(multiRound(dataList, temp + tmp, index + 1));
//                out.append(multiRound(dataList, temp + "  " + index, index + 1));
            }
            //判断是否已经完了一个回合，完了就加入到集合中
            if (index == dataList.size() - 1) {
                out.append(temp).append(tmp).append("\n");
            }
        }
        return out.toString();
    }

    /**
     * 收起键盘
     * author 易汉渊
     *
     * @param
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void hideKeyboard2(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }

//    /**
//     * 点击空白区域隐藏键盘.
//     */
//    @Override
//    public boolean dispatchTouchEvent(MotionEvent me) {
//        if (me.getAction() == MotionEvent.ACTION_DOWN) {  //把操作放在用户点击的时候
//            View v = getCurrentFocus();      //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
//            if (isShouldHideKeyboard(v, me)) { //判断用户点击的是否是输入框以外的区域
//                hideKeyboard(v.getWindowToken());   //收起键盘
//            }
//        }
//        return super.dispatchTouchEvent(me);
//    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {  //判断得到的焦点控件是否包含EditText
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],    //得到输入框在屏幕中上下左右的位置
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击位置如果是EditText的区域，忽略它，不收起键盘。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略
        return false;
    }
}
